/**
 * 移动端新版状态管理模块
 */
import api from '@/api'
import { Toast } from 'vant'
import { retryRequest, cacheRequestData, getCachedRequestData } from '@/utils/request-utils'

// 从localStorage读取数据的辅助函数
const getLocalData = (key, defaultValue) => {
  try {
    const data = localStorage.getItem(key)
    return data ? JSON.parse(data) : defaultValue
  } catch (error) {
    console.error(`获取本地存储数据失败: ${key}`, error)
    return defaultValue
  }
}

// Define ALL possible secondary functions with unique string IDs
const allAvailableFunctions = [
  // Finance
  { id: 'finance-expense', name: '费用报销', icon: 'balance-list-o', path: '/new/finance/expense', iconBg: 'blue', hidden: false },
  { id: 'finance-invoice', name: '发票管理', icon: 'bill-o', path: '/new/finance/invoice', iconBg: 'blue', hidden: false },
  { id: 'finance-salary', name: '工资查询', icon: 'gold-coin-o', path: '/new/finance/salary', iconBg: 'blue', hidden: false },
  { id: 'finance-budget', name: '预算管理', icon: 'chart-trending-o', path: '/new/finance/budget', iconBg: 'blue', hidden: false },
  { id: 'finance-travel-apply', name: '出差申请', icon: 'logistics', path: '/new/finance/travel/apply', iconBg: 'blue', hidden: false },
  { id: 'finance-travel-list', name: '我的出差', icon: 'notes-o', path: '/new/finance/travel/list', iconBg: 'blue', hidden: false },
  // Placeholders (can be added if implemented)
  // { id: 'finance-apply', name: '财务申请', icon: 'cash-o', path: '#', iconBg: 'gray', hidden: false },
  // { id: 'finance-travel-standard', name: '差旅标准', icon: 'description', path: '#', iconBg: 'gray', hidden: false },

  // Material
  { id: 'material-apply', name: '物资申领', icon: 'shopping-cart-o', path: '/new/material/apply', iconBg: 'green', hidden: false },
  { id: 'material-list', name: '库存查询', icon: 'list-switch', path: '/new/material/list', iconBg: 'green', hidden: false },
  { id: 'material-inbound', name: '采购验收', icon: 'down', path: '/new/material/inbound', iconBg: 'green', hidden: false },
  { id: 'material-outbound', name: '调拨验收/出库', icon: 'upgrade', path: '/new/material/outbound', iconBg: 'green', hidden: false },
  { id: 'material-inventory', name: '物资盘点', icon: 'todo-list-o', path: '/new/material/inventory', iconBg: 'green', hidden: false },
  { id: 'material-consumption', name: '物资消费', icon: 'chart-trending-o', path: '/new/material/consumption', iconBg: 'green', hidden: false }, // Assuming icon

  // Asset
  { id: 'asset-list', name: '资产列表', icon: 'records', path: '/new/asset/list', iconBg: 'purple', hidden: false },
  { id: 'asset-apply', name: '资产领用', icon: 'edit', path: '/new/asset/apply', iconBg: 'purple', hidden: false },
  { id: 'asset-repair', name: '资产维修', icon: 'setting-o', path: '/new/asset/repair', iconBg: 'purple', hidden: false },
  { id: 'asset-inventory', name: '资产盘点', icon: 'list-o', path: '/new/asset/inventory', iconBg: 'purple', hidden: false },
  { id: 'asset-dispose', name: '资产处置', icon: 'delete-o', path: '/new/asset/dispose', iconBg: 'purple', hidden: false },
  { id: 'asset-transfer', name: '资产调拨', icon: 'exchange', path: '/new/asset/transfer', iconBg: 'purple', hidden: false },
]

// Default functions shown on the homepage initially (subset of allAvailableFunctions)
const defaultFunctions = [
  allAvailableFunctions.find(f => f.id === 'finance-expense'),
  allAvailableFunctions.find(f => f.id === 'material-apply'),
  allAvailableFunctions.find(f => f.id === 'asset-list'),
  allAvailableFunctions.find(f => f.id === 'finance-invoice'),
  allAvailableFunctions.find(f => f.id === 'material-list'),
  allAvailableFunctions.find(f => f.id === 'asset-apply'),
].filter(f => f); // Filter out potential undefined if IDs change

export default {
  namespaced: true,
  
  state: {
    // All possible functions user can add
    allAvailableFunctions: allAvailableFunctions,

    // Current functions displayed on homepage (persisted)
    functionList: getLocalData('mobileFunctionList', defaultFunctions),
    
    // 最近访问
    recentVisits: getLocalData('mobileRecentVisits', []),
    
    // 消息中心
    messageCenter: {
      unreadCount: 0,
      todoList: [],
      processList: [],
      noticeList: [],
      announcementList: []
    },
    
    // 搜索历史
    searchHistory: getLocalData('mobileSearchHistory', []),
    
    // 应用状态 (最近打开的标签页等)
    appState: {
      homeActiveTab: 0, // 首页标签默认选中首个
      appActiveTab: 0   // 应用中心默认选中首个标签
    },
    
    // 全局loading状态
    loading: false,
    
    // 常用应用 (Keep this consistent or remove if redundant)
    favoriteApps: getLocalData('mobileFavoriteApps', defaultFunctions), // Use same default?
  },
  
  getters: {
    // Get functions currently displayed on homepage
    visibleFunctions: state => {
      return state.functionList.filter(item => !item.hidden)
    },
    // Get functions available to be added (all - current)
    availableFunctionsToAdd: state => {
      const currentIds = new Set(state.functionList.map(f => f.id));
      return state.allAvailableFunctions.filter(f => !currentIds.has(f.id));
    },
    
    // 获取所有未读消息数量
    totalUnreadCount: state => {
      return state.messageCenter.unreadCount
    },
    
    // 获取最近一周的访问记录
    recentWeekVisits: state => {
      const oneWeekAgo = new Date()
      oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)
      
      return state.recentVisits.filter(item => {
        const visitTime = new Date(item.timestamp)
        return visitTime >= oneWeekAgo
      })
    }
  },
  
  mutations: {
    // 设置功能列表 (Used for reordering)
    SET_FUNCTION_LIST(state, list) {
      state.functionList = list
      localStorage.setItem('mobileFunctionList', JSON.stringify(list))
      // Maybe update favoriteApps too if they should always match?
      // state.favoriteApps = list
      // localStorage.setItem('mobileFavoriteApps', JSON.stringify(list))
    },
    
    // Add a function to the list
    ADD_FUNCTION(state, func) {
      const exists = state.functionList.some(item => item.id === func.id);
      if (!exists) {
        state.functionList.push({ ...func, hidden: false }); // Ensure hidden is false when added
        localStorage.setItem('mobileFunctionList', JSON.stringify(state.functionList));
        // Maybe update favoriteApps too?
        // state.favoriteApps.push({ ...func, hidden: false });
        // localStorage.setItem('mobileFavoriteApps', JSON.stringify(state.favoriteApps));
      }
    },

    // Remove a function from the list by id
    REMOVE_FUNCTION(state, id) {
      state.functionList = state.functionList.filter(item => item.id !== id);
      localStorage.setItem('mobileFunctionList', JSON.stringify(state.functionList));
      // Maybe update favoriteApps too?
      // state.favoriteApps = state.favoriteApps.filter(item => item.id !== id);
      // localStorage.setItem('mobileFavoriteApps', JSON.stringify(state.favoriteApps));
    },
    
    // 切换功能可见性
    TOGGLE_FUNCTION_VISIBILITY(state, id) {
      const index = state.functionList.findIndex(item => item.id === id)
      if (index !== -1) {
        state.functionList[index].hidden = !state.functionList[index].hidden
        localStorage.setItem('mobileFunctionList', JSON.stringify(state.functionList))
      }
    },
    
    // 添加最近访问
    ADD_RECENT_VISIT(state, visit) {
      // 检查是否已存在相同路径
      const existIndex = state.recentVisits.findIndex(item => item.path === visit.path)
      
      // 如果存在，先移除旧记录
      if (existIndex !== -1) {
        state.recentVisits.splice(existIndex, 1)
      }
      
      // 添加到数组开头
      state.recentVisits.unshift({
        ...visit,
        timestamp: new Date().toISOString()
      })
      
      // 限制最大数量为10条
      if (state.recentVisits.length > 10) {
        state.recentVisits.pop()
      }
      
      // 保存到本地存储
      localStorage.setItem('mobileRecentVisits', JSON.stringify(state.recentVisits))
    },
    
    // 清空最近访问
    CLEAR_RECENT_VISITS(state) {
      state.recentVisits = []
      localStorage.removeItem('mobileRecentVisits')
    },
    
    // 设置消息列表
    SET_MESSAGE_LIST(state, { type, list }) {
      state.messageCenter[`${type}List`] = list
    },
    
    // 设置未读消息数量
    SET_UNREAD_COUNT(state, count) {
      state.messageCenter.unreadCount = count
    },
    
    // 添加搜索历史
    ADD_SEARCH_HISTORY(state, keyword) {
      if (!keyword.trim()) return
      
      // 检查是否已存在
      const index = state.searchHistory.indexOf(keyword)
      if (index !== -1) {
        state.searchHistory.splice(index, 1)
      }
      
      // 添加到数组开头
      state.searchHistory.unshift(keyword)
      
      // 限制最大数量为10条
      if (state.searchHistory.length > 10) {
        state.searchHistory.pop()
      }
      
      // 保存到本地存储
      localStorage.setItem('mobileSearchHistory', JSON.stringify(state.searchHistory))
    },
    
    // 清空搜索历史
    CLEAR_SEARCH_HISTORY(state) {
      state.searchHistory = []
      localStorage.removeItem('mobileSearchHistory')
    },
    
    // 更新应用状态
    UPDATE_APP_STATE(state, { key, value }) {
      state.appState[key] = value
    },
    
    // 设置加载状态
    SET_LOADING(state, status) {
      state.loading = status
    }
  },
  
  actions: {
    // 保存功能排序
    saveFunctionOrder({ commit }, list) {
      commit('SET_FUNCTION_LIST', list)
    },
    
    // Add a function
    addFunction({ commit, state }, func) {
      const exists = state.functionList.some(item => item.id === func.id);
      if (!exists) {
        commit('ADD_FUNCTION', func)
      } else {
        Toast('该功能已在常用功能中');
      }
    },

    // Remove a function
    removeFunction({ commit }, id) {
      commit('REMOVE_FUNCTION', id)
    },
    
    // 切换功能可见性
    toggleFunctionVisibility({ commit }, id) {
      commit('TOGGLE_FUNCTION_VISIBILITY', id)
    },
    
    // 记录访问历史
    recordVisit({ commit }, visit) {
      commit('ADD_RECENT_VISIT', visit)
    },
    
    // 清空访问历史
    clearVisitHistory({ commit }) {
      commit('CLEAR_RECENT_VISITS')
    },
    
    // 加载消息数据
    async loadMessages({ commit, state }, { retry = 3, delay = 1000 } = {}) {
      try {
        commit('SET_LOADING', true)
        
        // 尝试从缓存获取数据
        const cachedData = getCachedRequestData('mobileMessages')
        if (cachedData) {
          const { todo, process, unreadCount } = cachedData
          commit('SET_MESSAGE_LIST', { type: 'todo', list: todo })
          commit('SET_MESSAGE_LIST', { type: 'process', list: process })
          commit('SET_UNREAD_COUNT', unreadCount)
        }
        
        // 加载待办消息
        const todoRes = await retryRequest(
          () => api.todo.getTodoList(),
          retry,
          delay
        )
        if (todoRes && todoRes.code === 0) {
          commit('SET_MESSAGE_LIST', { type: 'todo', list: todoRes.data })
        }
        
        // 加载流程消息
        const processRes = await retryRequest(
          () => api.profile.getNotifications({ type: 'process' }),
          retry,
          delay
        )
        if (processRes && processRes.code === 0) {
          commit('SET_MESSAGE_LIST', { type: 'process', list: processRes.data })
        }
        
        // 获取未读消息总数
        const unreadRes = await retryRequest(
          () => api.profile.getUnreadCount(),
          retry,
          delay
        )
        if (unreadRes && unreadRes.code === 0) {
          commit('SET_UNREAD_COUNT', unreadRes.data)
        }
        
        // 缓存新数据
        cacheRequestData({
          todo: state.messageCenter.todoList,
          process: state.messageCenter.processList,
          unreadCount: state.messageCenter.unreadCount
        }, 'mobileMessages')
        
      } catch (error) {
        console.error('加载消息失败', error)
        
        if (!getCachedRequestData('mobileMessages')) {
          Toast({
            message: '消息加载失败，请检查网络连接',
            duration: 3000
          })
        }
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 搜索功能
    async search({ commit, state }, keyword) {
      if (!keyword.trim()) return []
      
      try {
        commit('SET_LOADING', true)
        commit('ADD_SEARCH_HISTORY', keyword)
        
        // 执行搜索 (示例，实际根据API调整)
        const response = await api.request.get('/api/search', { params: { keyword } })
        
        return response.data
      } catch (error) {
        console.error('搜索失败', error)
        Toast('搜索失败，请稍后重试')
        return []
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 清空搜索历史
    clearSearchHistory({ commit }) {
      commit('CLEAR_SEARCH_HISTORY')
    },
    
    // 初始化数据
    initData({ dispatch }) {
      dispatch('loadMessages')
    }
  }
} 